import asyncio
import threading
import time


class AsyncHelper:
    def __init__(self):
        self.loop = asyncio.new_event_loop()
        self.thread = threading.Thread(target=self.main_loop_run, daemon=True)
        self.thread.start()

    async def loop_run(self):
        count: int = 0
        self.loop = asyncio.get_running_loop()
        while True:
            print(f"loop run count:{count}")
            count += 1
            await asyncio.sleep(2)

    def main_loop_run(self):
        try:
            # 为当前线程创建独立的事件循环
            loop = self.loop
            asyncio.set_event_loop(loop)
            gather = asyncio.gather(self.loop_run())
            loop.run_until_complete(gather)
        except Exception as e:
            print(f"Task error: {e}")
        finally:
            if loop and not loop.is_closed():
                loop.close()

    def run_async(self, coro):
        """在主线程中调用，在异步线程中执行协程并返回结果"""
        future = asyncio.run_coroutine_threadsafe(coro, self.loop)
        return future.result()  # 这会阻塞直到协程完成


# 示例异步函数
async def async_operation(x, y):
    await asyncio.sleep(1)  # 模拟异步操作
    return x + y


# 使用示例
def main():
    helper = AsyncHelper()
    time.sleep(2)

    # 在主线程中调用异步函数
    ret = helper.run_async(async_operation(10, 20))
    print(f"跨线程异步调用 结果1: {ret}")


if __name__ == "__main__":
    main()
